package logic

import (
	"context"
	"shuqi-novel/models/cache"
	"shuqi-novel/models/mysql"
	"strconv"
	"time"

	"shuqi-novel/shuqirpc/internal/svc"
	"shuqi-novel/shuqirpc/shuqirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type NovelListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewNovelListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NovelListLogic {
	return &NovelListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *NovelListLogic) NovelList(in *shuqirpc.NovelListRequest) (*shuqirpc.NovelListResponse, error) {
	// todo: add your logic here and delete this line

	page, _ := strconv.Atoi(strconv.FormatInt(in.Page, 10))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(strconv.Itoa(5))
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	query := mysql.DB.Debug().Offset(offset).Limit(pageSize)

	var novel []mysql.Novel
	query.Where("user_id = ?", in.UserId).Find(&novel)

	var novelList []*shuqirpc.NovelList

	for _, m := range novel {
		list := shuqirpc.NovelList{
			Id:     int64(m.ID),
			Title:  m.Title,
			Author: m.Author,
			Info:   m.Info,
		}
		novelList = append(novelList, &list)
	}

	cache.Rdb.Set(l.ctx, "novelList", novelList, time.Minute*30)
	return &shuqirpc.NovelListResponse{List: novelList}, nil
}
